<?php

	include_once("./db.php"); 
	
	$userId = $_SESSION["user"]["Id"];

	$fields = array(
		"ElementName"	=> $_REQUEST["name"],
		"ElementAuthorId" => $userId
	); 
	
	$ar_elements[] = $_REQUEST["e1"];
	$ar_elements[] = $_REQUEST["e2"];
	
	$count = count($ar_elements);
	
	$elements = implode($ar_elements, ", ");
	
	//TODO:retornar tudo pra ja apresentar a discussao dessa combinacao
	$res = db_select("
		SELECT count(1) foundElements, e.Id FROM 
		Combination c,
		CombinationItem ci,
		Element e
		WHERE 
		c.Id = ci.CombinationId AND
		e.Id = c.ProductId AND
		ci.ElementId in ($elements) 
		GROUP BY e.Id
				HAVING foundElements = $count
				ORDER BY foundElements DESC, c.CreateDate ASC
				LIMIT 1");

	if(mysql_num_rows($res) != 0)
	{
		//TODO:insert user vote	
		return json_result_encode("This combination are already in pool. Your vote was computed.");
	}

	$fields = array(
		"ElementName"	=> $_REQUEST["name"],
		"ElementAuthorId" => $userId
	); 
	
	$element = db_insert("Element", $fields);
	
	if(!$element)
		return json_result_encode("Can't create element.");
		
		
	$fields = array(
		"TagElementElementId"	=> $element["Id"],
		"TagElementTagId" => 1
	); 
	
	$tag = db_insert("TagElement", $fields);
	
	if(!$tag)
		return json_result_encode("Can't create element tag.");
		
	
	$fields = array(
		"CombinationProductId"	=> $element["Id"],
		"CombinationAuthorId" => $userId
	); 
	
	$combination = db_insert("Combination", $fields);
		
	if(!$combination)
		return json_result_encode("Can't create combination.");

	
	$fields = array(
		"CombinationItemCombinationId"	=> $combination["Id"],
		"CombinationItemElementId" => $ar_elements[0]
	); 
	
	$combinationItem = db_insert("CombinationItem", $fields);
		
	if(!$combinationItem)
		return json_result_encode("Can't create combination items.");
	
		$fields = array(
		"CombinationItemCombinationId"	=> $combination["Id"],
		"CombinationItemElementId" => $ar_elements[1]
	); 
	
	$combinationItem = db_insert("CombinationItem", $fields);
		
	if(!$combinationItem)
		return json_result_encode("Can't create combination items.");

	//todo:return user post.		
	echo json_result_encode($ret);

?>

